logging.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import logging
  2. import sys
  3. import typing as t
  4. from werkzeug.local import LocalProxy
  5. from .globals import request
  6. if t.TYPE_CHECKING:
  7. from .app import Flask
  8. @LocalProxy
  9. def wsgi_errors_stream() -> t.TextIO:
  10. """Find the most appropriate error stream for the application. If a request
  11. is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.
  12. If you configure your own :class:`logging.StreamHandler`, you may want to
  13. use this for the stream. If you are using file or dict configuration and
  14. can't import this directly, you can refer to it as
  15. ``ext://flask.logging.wsgi_errors_stream``.
  16. """
  17. return request.environ["wsgi.errors"] if request else sys.stderr
  18. def has_level_handler(logger: logging.Logger) -> bool:
  19. """Check if there is a handler in the logging chain that will handle the
  20. given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.
  21. """
  22. level = logger.getEffectiveLevel()
  23. current = logger
  24. while current:
  25. if any(handler.level <= level for handler in current.handlers):
  26. return True
  27. if not current.propagate:
  28. break
  29. current = current.parent # type: ignore
  30. return False
  31. #: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format
  32. #: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.
  33. default_handler = logging.StreamHandler(wsgi_errors_stream) # type: ignore
  34. default_handler.setFormatter(
  35. logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")
  36. )
  37. def create_logger(app: "Flask") -> logging.Logger:
  38. """Get the Flask app's logger and configure it if needed.
  39. The logger name will be the same as
  40. :attr:`app.import_name <flask.Flask.name>`.
  41. When :attr:`~flask.Flask.debug` is enabled, set the logger level to
  42. :data:`logging.DEBUG` if it is not set.
  43. If there is no handler for the logger's effective level, add a
  44. :class:`~logging.StreamHandler` for
  45. :func:`~flask.logging.wsgi_errors_stream` with a basic format.
  46. """
  47. logger = logging.getLogger(app.name)
  48. if app.debug and not logger.level:
  49. logger.setLevel(logging.DEBUG)
  50. if not has_level_handler(logger):
  51. logger.addHandler(default_handler)
  52. return logger